/**
 * @description  : 公共文书待办页
 * @descriptionDetail : 公共文书待办页
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-12-03 14:00:29
 */
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
    </theme-navbar>
    <!-- #endif -->
    <view class="content u-page">
      <u-form v-model="formData" label-width="auto" label-position="top">
        <u-form-item :label="pi.title" v-for="pi in commonDoc.pageInfos" :key="pi.title">
          <view class="lay-file-root">
            <view class="lay-file" v-html="getContent(pi)">
            </view>
          </view>
        </u-form-item>
        <u-form-item label="当前环节">
          <view class="lay-file-root">
            <view class="lay-file">
              {{ docIns.stepName }}
            </view>
          </view>
        </u-form-item>
        <u-form-item label="文书" v-if="!commonDoc.noPdf">
          <view class="lay-file-root">
            <view class="lay-file" @click="toPrevView()">
              <text class="lay-file-title">
                {{ commonDoc.name }}
              </text>
            </view>
          </view>
        </u-form-item>
        <u-form-item label="备注" v-if="!!docData.memo">
          <view class="lay-file-root">
            <view class="lay-file">
              {{ docData.memo }}
            </view>
          </view>
        </u-form-item>
        <u-gap v-if="currApprove.show" :marginRight="getGapMarginRowNumber()" :marginLeft="getGapMarginRowNumber()" :height="$theme.cm_section_top_gap_height" :bg-color="$theme.cm_form_item_bottom_border_color"></u-gap>
        <fsection title="审批意见" v-if="currApprove.show">
        </fsection>
        <u-form-item label="" v-if="currApprove.show && agreeAndDisAgreeLogic && gfaCode == 'amendApply'">
          <u-radio-group v-model="radioVal" :disabled="radioDisabled" @change="radioGroupChange">
            <u-radio
              v-for="(item, index) in radioList"
              :key="'radio'+index"
              :name="item.name"
            >
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item :label="currApprove.gfaName" v-if="currApprove.show">
          <view class="approve-lay">
            <u-input v-model="currApprove.approveInfo" type="textarea" placeholder="请输入审核意见"></u-input>
            <view class="approve-lay-bt">
              <view>
                审核人: <text style="margin-left: 10rpx;color: #393B3D;">
                  {{ currApprove.approvePersonName }}
                </text>
              </view>
              <view style="text-align: right;" @click="onDatePick">
                审核时间: <text style="margin-left: 10rpx;color: #393B3D;">
                  {{ currApprove.approveDate }}
                </text>
              </view>
            </view>
          </view>
        </u-form-item>
        <u-gap :marginRight="getGapMarginRowNumber()" :marginLeft="getGapMarginRowNumber()" :height="$theme.cm_section_top_gap_height" :bg-color="$theme.cm_form_item_bottom_border_color"></u-gap>
        <fsection title="审批历史"></fsection>
        <u-form-item label="" :border-bottom="false">
          <view style="width: 100%;color: #000000;margin-left: 20rpx;">
            <flow-his :approve="flowHis" :haveEnd="haveEnd"></flow-his>
          </view>
        </u-form-item>
      </u-form>
    </view>
    <view class="submit-btns btn-other-cls" v-if="docIns.step != 'view' && docIns.step != 'edit' && allowBtnShow">
      <u-button class="u-btn" size="default" type="error" @click="returnAudit">
        {{ btns[0] }}
      </u-button>
      <u-button class="u-btn" size="default" type="primary" @click="submitAudit">
        {{ btns[1] }}
      </u-button>
    </view>
    <u-calendar mode="date" v-model="calShow" @change="dateConfirm"></u-calendar>
  </view>
</template>

<script>
import {
  COMMON_DOC,
} from "@/service/enum/common-doc";
import commonService from "@/service/common/common.service";
import flowHis from "@/components/flow-his.vue";
import fsection from "@/components/form-section.vue";
export default {
  components:{flowHis,fsection,},
  data() {
    return {
      titleStyle:{
        color:'#000000',
        fontWeight:'bold',
        fontSize:'18px',
      },
      confirmStyle:{
        color:'#fff',
        background:'#0487FB',
        borderRadius:'12px',
        fontSize:'14px',
        height:'40px',
        lineHeight:'40px',
        margin:'20px',
      },
      user: this.$store.state.userInfo.user,
      calShow: false,
      iconCustomStyle: {
        color: this.$theme.u_type_primary,
      },
      valueStyle: {
        color: "#000000",
      },
      gfaCode: "",
      commonDoc: {},
      docIns: {},
      formData:{},
      flowHis: [],
      approves: [],
      currApprove:{
        show:false,
        approveInfo:"",
      },
      docData: {},
      initAppDate: this.$u.date(Date.now(), 'yyyy-mm-dd'),
      tmpParam: undefined,
      showPdf:true,
      preParam:{},
      haveEnd:false,
      // isDisabled:false,
      btns:["退回", "审批通过",],
      allowBtnShow: true,
      agreeAndDisAgreeLogic: false, // 是否存在同意不同意强检逻辑
      radioList:[],
      radioDisabled: false,
      radioVal:"",
    }
  },
  onLoad() {
    this.preParam = this.getRouteParam();
    this.showDefaultTitle = false;
  },
  mounted() {
    this.initDocData();
  },
  methods: {
    onDatePick() {
      this.calShow = true;
    },
    getGapMarginRowNumber(){
      return "-" + this.$theme.cm_content_paddng_row.replace('rpx', '');
    },
    dateConfirm(e) {
      this.initAppDate = e.result;
      if(this.currApprove){
        this.currApprove.approveDate = this.$u.timeFormat((new Date(e.result)).getTime(), 'yyyy年mm月dd日');
      }
    },
    getContent(pi){
      let type = pi.type || 0;
      if(type == 0){
        return this.docData[pi.column];
      }else if(type == 1){
        let arr = this.docData[pi.column];
        let strArr = [];
        if(arr && arr.length > 0){
          arr.forEach(ix => {
            strArr.push(ix[pi.arrColum]);
          });
        }
        return strArr.join('<br/>');
      }
      return "";
    },
    updateBackState(param) {

      if (param.auditApprove) { // 审批意见页面返回
        let pa = {};
        pa.approveInfo = param.auditApprove.remark;
        pa.isAgree = param.auditApprove.isAgree;
        this.beforeAgreeSubmit(pa);
      } else if (param.flowUserSelectBack) { // 选择审批人
        let nextPersons = [];
        for (let fu of param.flowUserSelectBack) {
          nextPersons.push(fu.personId);
        }
        this.doSubmit(this.tmpParam, nextPersons.join(","));
      }
    },
    returnAudit() {
      let da = {};
      da.docInsUuid = this.docIns.docInsUuid;
      da.docUuid = this.docIns.docUuid;
      da.titemUuid  = this.docIns.configIns.titemUuid;
      da.gfaCode = this.docIns.step;

      da.isAgree = 0;
      da.approvePersonUuid = this.user.personUuid;
      da.opType = "3"; // 3 表示退回
      if(!this.agreeAndDisAgreeLogic){
        da.approveInfo = this.currApprove.approveInfo;
        if (!da.approveInfo || da.approveInfo == this.currApprove.flowNode?.agreeText) {
          da.approveInfo = this.currApprove.approveInfo = this.currApprove.flowNode?.disagreeText;
        }
      } else {
        da.approveInfo = this.currApprove.approveInfo;
      }
      // 执行退回操作
      this.doReturn(da);
    },
    /**
	 * 退回操作
	 */
    doReturn(da) {
      this.$modal.confirm('确定要退回吗?', () => {
        this.$modal.showLoading('退回中...');
        let returnPromise = this.calcPromise("back", da);
        let self = this;
        returnPromise.then((rs) => {
          self.$modal.hideLoading();
          if(rs.success){
            self.backPrev({
              paramKey: "refresh",
              param: true,
            });
          }else{
            self.$modal.alert(rs.msg);
          }
        }, (err) => {
          self.$modal.hideLoading();
          self.$modal.alert(err.msg);
        });
      });
    },
    submitAudit() {
      let da = {};
      let currStep = this.docIns.step;
      // 审核审批通过扩展页面补充信息
      if (this.commonDoc['nodeForm'] && this.commonDoc['nodeForm'].includes(currStep) ) {
        da.opType = 1;
        da.docInsUuid = this.docIns.docInsUuid;
        da.docUuid = this.docIns.docUuid;
        da.gfaCode = currStep;
        da.titemUuid = this.docIns.configIns.titemUuid;
        da.approvePersonUuid = this.user.personUuid;
        da.isAgree = 1;
        da.approveInfo = '同意';
        this.toDocPage(da);
        return;
      }
      if(!this.agreeAndDisAgreeLogic){
        da.isAgree = 1;
      }else{
        if(this.currApprove.isAgree == 1 || this.currApprove.isAgree == 0){
          da.isAgree = this.currApprove.isAgree;
        }else{
          if(this.gfaCode  == "amendApply"){ // 如果时文书删改这必填
            this.$u.toast('请选择审批意见');
            return;
          }
          da.isAgree = 1;
        }
      }
      da.approveInfo = this.currApprove.approveInfo;
      if (!da.approveInfo) {
        da.approveInfo = this.currApprove.approveInfo = this.currApprove.flowNode?.agreeText;
      }
      this.beforeAgreeSubmit(da);
    },
    /**
			 * 审核审批通过之前的数据组装
			 */
    beforeAgreeSubmit(da) {
      da.opType = 1;
      da.docInsUuid = this.docIns.docInsUuid;
      da.docUuid = this.docIns.docUuid;
      da.gfaCode = this.docIns.step;
      da.titemUuid = this.docIns.configIns.titemUuid;
      da.approvePersonUuid = this.user.personUuid;

      // 审核时选择审批节点人员
      if (this.approves.length == 0) {
        this.$modal.alert("当前待办没有流程");
        return;
      }
      // 如果当前不是结束节点则选择审核审批人员
      if (this.docIns.step !== this.approves[this.approves.length - 1].gfaCode) {
        let flag =  (this.docIns.configIns.flowFormCode == 'docBigCaseApplyReport' && this.docIns.step == '01') ? '0' : '1';
        let model = ['cityCaseSeriousReward','caseSeriousApply','cityProvCaseSeriousReward',];
        flag = model.includes(this.docIns.configIns.flowFormCode) ? '0' : flag;
        this.tmpParam = da;
        this.$u.route({
          url: "/pages/commonPage/flowUserSelectComponent",
          params: {
            flowFormCode: this.docIns.configIns.flowFormCode,
            docInsUuid: this.docIns.docInsUuid,
            needLevel: flag,
          },
        });
      } else {
        this.doSubmit(da);
      }
    },
    /**
	 * 执行提交操作
	 */
    doSubmit(da, nextPersons) {
      this.$modal.showLoading(this.docIns.step === "01" ? "审核中..." : "审批中...");
      da.nextPersons = nextPersons;
      let submitPromise = this.calcPromise("submit", da);
      submitPromise.then((rs) => {
        this.$modal.hideLoading();
        if (rs.success) {
          // if(nextPersons){
          this.backPrev({
            paramKey: "refresh",
            param: true,
          });
        } else {
          this.$modal.alert(rs.msg);
        }
      }, (err) => {
        this.$modal.hideLoading();
        // this.alert(err.msg);
      });
    },
    /**
	 * 初始化文书信息
	 */
    initDocData() {
      this.$modal.showLoading("文书加载中...");
      let self = this;
      this.gfaCode = this.preParam["gfCode"];
      if(this.gfaCode == 'dirReplenish'){  // 是拆卷申请则不展示文书选项
        this.showPdf = false;
      }
      this.commonDoc = COMMON_DOC[this.gfaCode];
      this.agreeAndDisAgreeLogic = this.commonDoc.agreeAndDisAgreeLogic || false;
      this.navTitle = this.commonDoc.name;
      // 文书实例信息
      commonService.getDocIns(this.preParam['docInsUuid']).then((res) => {
        this.updateTitle();
        self.$modal.hideLoading();
        if (res.success) {
          self.docIns = res.bean;
          if(!this.$u.test.isEmpty(this.commonDoc.restrictNodes)){
            let arr = this.commonDoc.restrictNodes.split(',');
            this.allowBtnShow = !arr.includes(this.docIns.step);
          }
          this.haveEnd = this.getHaveHisEnd();
          // 文书信息1
          self.initDoc();
          Promise.all([commonService.approves({id: self.docIns.docInsUuid,docUuid: self.docIns.docUuid,}),
            commonService.flowHis({ gfCode: self.docIns.configIns.docCode, docInsUuid: self.docIns.docInsUuid,}),
          ]).then(resp => {
            let approves = resp[0];
            self.approves = approves.data || [];
            let flowNode;
            for (let i = 0; i < self.approves.length ; i++) {
              let a = self.approves[i];
              if(a.gfaCode === this.docIns.step) {
                flowNode = a.flowNode || undefined;
                a.approveDate = this.$u.timeFormat(Date.now(), 'yyyy年mm月dd日');
                a.approvePersonUuid = this.user.personUuid;
                a.approvePersonName = this.user.personName;
                a.approveInfo =  a.flowNode?.agreeText; // this.agreeAndDisAgreeLogic ? a.flowNode?.agreeText : ""; // a.flowNode?.agreeText
                a.show = true;
                this.updateBtns(a.flowNode);
                this.currApprove = a || {};
                break;
              }
            }
            if(flowNode){
              this.radioList.push({
                name: flowNode.agreeText,
                value: 1,
              });
              this.radioList.push({
                name: flowNode.disagreeText,
                value: 0,
              });
            }
            self.flowHis = resp[1].data || [];
            if(this.agreeAndDisAgreeLogic){
              let neviList = self.flowHis.reverse();
              for (let i = 0; i < neviList.length; i++) {
                if(neviList[i].gfaCode == 'start' && flowNode){
                  if(neviList[i].isAgree == 1){
                    this.currApprove.approveInfo = flowNode.agreeText;
                    this.currApprove.isAgree = 1;
                    this.radioDisabled = true;
                  }else if(neviList[i].isAgree == 0){
                    this.currApprove.approveInfo = flowNode.disagreeText;
                    this.currApprove.isAgree = 0;
                    this.radioDisabled = true;
                  }
                  break;
                }
              }
            }
          }).catch(e => {
            console.log(e);
          });
          // self.pallFun(orgLevel);
        } else {
          this.$modal.hideLoading();
          this.$modal.alert("查询出错:" + res.msg);
        }
      }).catch(err => {
        this.$modal.hideLoading();
        this.updateTitle();
        this.$modal.alert("查询出错:" + err);
      });
    },

    radioGroupChange(e){
      let ap = this.radioList.filter(it => {
        return it.name == e;
      });
      if(ap && ap.length > 0){
        this.currApprove.approveInfo = ap[0].name;
        this.currApprove.isAgree = ap[0].value;
      }
    },
    updateBtns(node){
      try{
        let p = this.commonDoc.btns[this.docIns.step];
        if(p){
          this.btns[0] = p[0];
          this.btns[1] = p[1];
        }
      }catch(e){
        console.log(e)
      }
    },
    updateTitle(){
        this.$deviceApi.setTitle && this.$deviceApi.setTitle(COMMON_DOC[this.gfaCode].name);
        this.navTitle = COMMON_DOC[this.gfaCode].name;
        this.$forceUpdate();
    },
    /**
		 * 获取文书信息
		 */
    initDoc() {
      let self = this;
      let docParam = {
        id: this.docIns.docInsUuid,
        docUuid: this.docIns.docUuid,
        bizUuid: this.docIns.bizUuid,
      };
      let initPromise = this.calcPromise("init", docParam);
      initPromise.then((rs) => {
        self.$modal.hideLoading();
        if (rs.success) {
          console.log(rs);
          let docData1 = rs.data || [];
          this.docData = {};
          docData1.forEach(d => {
            Object.assign(this.docData,d);
          });
          if(this.docIns.step == 'edit'){
            this.$u.toast('已打回发起人，请重新编辑提交!');
          }else if(!this.allowBtnShow){
            this.$modal.alert("请前往pc端操作", () => {
              uni.navigateBack();
            });
          }
        } else {
          self.$modal.alert(rs.msg);
        }
      }, (err) => {
        self.$modal.hideLoading();
      });
    },
    calcPromise(type, param) {
      // 审核审批时间
      if (type != 'init') {
        param.approveDate = this.currApprove ? this.currApprove.approveDate : this.$u.timeFormat((new Date(this.initAppDate)).getTime(), 'yyyy年mm月dd日');
      }
      // 废弃处置
      // if (this.commonDoc.parent == "FQCZ") {
      return this.calcCasePromise(type, param);
      // }
    },
    /**
		 * 获取文书信息初始化、提交、退回接口的Promise
		 */
    calcCasePromise(type, param) {
      let funType = this.commonDoc.functions[type];
      let promise = null;
      switch (type) {
      case "init": // 初始化
        promise = commonService.getDoc(param, this.docIns.configIns.controllerPath, this.docIns.configIns.docType);
        break;
      case "submit": // 提交
        promise = commonService.agree(this.docData,this.docIns.configIns.controllerPath, param,this.docIns.configIns.docType);
        break;
      case "back": // 退回上一步
        if(param.opType == 2){
          promise = commonService.disagree(this.docData,
            this.docIns.configIns.controllerPath,
            param,
            this.docIns.configIns.docType);
        }else{
          promise = commonService.backToFirst(this.docData,
            this.docIns.configIns.controllerPath,
            param,
            this.docIns.configIns.docType);
        }
        break;
      default:
        break;
      }
      return promise;
    },
    getCustomPrex(type) {
      if (type == 1) {
        return "csbi-icon";
      } else if (type == 2) {
        return "uicon";
      } else if (type == 3) {
        return "uicon";
      } else if (type == 4) {
        return "uicon";
      }else{
        return "";
      }
    },
    getIconName(type) {
      if (type == 1) {
        return "daochu";
      } else if (type == 2) {
        return "account";
      } else if (type == 3) {
        return "calendar";
      } else if (type == 4) {
        return "chat";
      }else {
        return "";
      }
    },
    toPrevView(){
      if(this.commonDoc.parent !== 'FQCZ'){
        this.downloadFile();
      }else{
        this.toDocPage();
      }
    },
    toDocPage(data){
      let currType;
      if(this.docIns.docCode == 'punishDeclarOther'){
        currType = 1;
      }else if(this.docIns.docCode == 'punishDeclarFertilizer'){
        currType = 0;
      }
      let params = {
        bizUuid:this.docIns.bizUuid,
        currType:currType,
        step:this.docIns.step,
        isDone: this.docIns.step != 'view',
      };
      if(data){
        params.da = {...data,};
      }else{
        let da = {};
        let currStep = this.docIns.step;
        // 审核审批通过扩展页面补充信息
        if (this.commonDoc['nodeForm'] && this.commonDoc['nodeForm'].includes(currStep) ) {
          da.opType = 1;
          da.docInsUuid = this.docIns.docInsUuid;
          da.docUuid = this.docIns.docUuid;
          da.gfaCode = currStep;
          da.titemUuid = this.docIns.configIns.titemUuid;
          da.approvePersonUuid = this.user.personUuid;
          da.isAgree = 1;
          da.approveInfo = '同意';
          params.da = {...da,};
        }
      }
      this.setRouteParam(params);
      this.$u.route({
        url:this.commonDoc.url,
        type:"redirect",
      });
    },
    getHaveHisEnd(){
      return this.docIns.step == 'view'
    },
    downloadFile(){
      if(this.$u.test.isEmpty(this.docIns.pdfFileId)){
        this.$u.toast('文书PDF不存在');
        return;
      }
      // 定义跳转参数
      const params = {
        fileId: this.docIns.pdfFileId,
        fileName: this.commonDoc.name,
      };
      this.setRouteParam(params);
      // 跳转详情页面
      this.$u.route("/pages/commonPage/printerComponent");
    },
  },
}
</script>

<style scoped lang="scss">
	.page{
		padding: 0;
	}
	.content {
		padding-bottom: 70px;
		padding-left: $cm-content-paddng-row;
		padding-right: $cm-content-paddng-row;
	}

	.item-inner .item-title.label {
		width: 35%;
	}

	.display-flex {
		display: flex !important;
		justify-content: center;
		align-items: center;
	}

	.input-label {
		min-width: 80px;
		display: flex;
		justify-content: center;
		align-items: center;

		input[type='radio'],
		input[type='checkbox'] {
			width: 14px;
		}
	}

	.article-title {
		text-align: center;
		background-color: #FFF;
	}

	.article-main-title {
		color: #000000;
		font-size: 18px;
		text-align: center;
		color: #000;
		font-weight: 600;
	}

	.article-sub-title {
		font-size: 15px;
		margin: 3px;
	}

	.article-content-detail {
		margin: 3px;
		text-align: center;
		color: #000;
		height: 22px;
		font-size: 13px;
	}

	.basic-info:after {
		display: none;
	}

	.auditList:before {
		display: none;
	}

	.basic-info li:last-child .item-inner {
		border-bottom: 0.5px solid #E6E6E8;
	}

	.long-txt {
		width: 65%;
		white-space: normal;
		max-height: 150px;
		overflow-y: auto;
	}

	.list textarea {
		height: 60px;
		font-size: 13px;
		border: 1px groove;
		padding: 5px;
	}

	.list textarea:disabled {
		border: none;
	}

	.item-content-detail img {
		height: 12px;
	}

	.returnAudit {
		color: #000 !important;
	}

	.part-title {
		text-align: center;
		font-weight: 600;
		padding: 6px;
		background-color: #fff;
		font-size: 14px;
	}

	.text-label {
		color: #000;
		text-align: left;
	}

	.lay-root {
		width: 100%;
		display: inline-flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.lay-title {
		align-self: center;
		flex-shrink: 0;
		font-size: 32rpx;
	}

	.block {
		padding: 10px 0px;
	}

	.lay-content {
		align-self: center;
		word-wrap: break-word;
		word-break: break-all;
		font-size: 28rpx;
		white-space: normal;
		overflow: hidden;
	}

	.lay-file-root {
		display: flex;
		flex-direction: column;
	}

	.lay-file {
		align-self: flex-end;
		display: inline-flex;
		flex-direction: row;
		align-items: center;
	}

	.timeline-item {
		padding: 2px 0px 15px;
		display: flex;
		justify-content: flex-start;
		overflow: hidden;
		box-sizing: border-box;
		position: relative;
	}

	.lay-file-title {
		font-size: 30rpx;
		color: $u-type-primary;
	}

	.timeline-todo {
		background-color: red !important;
	}

	.timeline-finish {
		background-color: green !important;
	}

	.timeline-item-date {
		width: 100px;
		flex-shrink: 0;
		text-align: right;
		box-sizing: border-box;
	}

	.timeline-item-divider {
		margin-left: 15px;
		margin-right: 15px;
		position: relative;
		width: 10px;
		height: 10px;
		background: #bbb;
		border-radius: 50%;
		margin-top: 3px;
		flex-shrink: 0;
	}

	.timeline-item-divider:after {
		top: 100%;
	}

	.timeline-item-divider:before {
		bottom: 100%;
	}

	.timeline-item-divider:after,
	.timeline-item-divider:before {
		background-color: #c7c2c2;
		content: ' ';
		width: 1px;
		height: 100vh;
		position: absolute;
		left: 50%;
		transform: translate3d(-50%, 0, 0);
	}

	.timeline-item:last-child .timeline-item-divider:after {
		display: none;
	}

	.timeline-item:first-child .timeline-item-divider:before {
		display: none;
	}

	.timeline-item-content {
		margin: 2px;
		min-width: 0;
		position: relative;
		flex-shrink: 10;
		text-align: left;
	}

	.timeline-item-title {
		font-size: 17px;
		font-weight: 600;
	}

	.slot-content {
		padding: 30rpx;
	}
	.approve-lay{
		width: 100%;
	}
	.approve-lay-bt{
		width: 100%;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		display: inline-flex;
		flex-direction: row;
		color: $cm-form-item-label-color;
		justify-content: space-between;
		align-items: center;
		font-size: 28rpx;
	}
	/deep/uni-button {
		width: 40%;
	}
</style>
